package svgedit.gui.actions;

import java.awt.event.ActionEvent;
import java.io.File;
import java.io.IOException;

import javax.swing.AbstractAction;
import javax.swing.JOptionPane;

import svgedit.gui.FileChooserDialog;
import svgedit.gui.Frame;
import svgedit.gui.SupportedFiles;

/**
 * Shows a file dialog for the user to select a new file to write the document
 * to, then saves it at that location.
 */
@SuppressWarnings("serial")
public class SaveDocumentAsAction
	extends AbstractAction
{

    private Frame frame;

    /** Create this action for the given frame */
    public SaveDocumentAsAction(Frame frame)
    {
	super("Save As...");
	this.frame = frame;
    }

    @Override
    public void actionPerformed(ActionEvent arg0)
    {
	File file = frame.getDocument().getFile();
	FileChooserDialog dialog;
	if (file != null)
	    dialog =
		    new FileChooserDialog(
			    FileChooserDialog.FILE_SAVEAS_DIALOG, file);
	else
	    dialog =
		    new FileChooserDialog(
			    FileChooserDialog.FILE_SAVEAS_DIALOG, frame
				    .getPreferences().getDefaultPath());

	if (!(dialog.showSaveDialog(frame) == FileChooserDialog.APPROVE_OPTION))
	    return;

	file = dialog.getSelectedFile();


	SupportedFiles filter = (SupportedFiles) dialog.getFileFilter();

	if (filter == SupportedFiles.FileFilters.STAR_DOT_STAR)
	{
	    if (!(SupportedFiles.FileFilters.SVG_FILES_FILTER.validExt(file)))
	    {
		System.err.println("Unsupported extension. Meh?");
	    }
	}
	    
	file = SupportedFiles.ensureExtension(file, filter);

	file = checkOverwrite(file);
	if (file == null)
	    return;

	frame.getPreferences().setDefaultPath(file.getPath());
	frame.saveFile(file);
    }

    /**
     * If supplied file already exists ask the user to confirm overwrite
     * Set fill to null if they decline.
     * @param file
     * @return file
     */
    public static File checkOverwrite(File file)
    {
	if (file != null && file.exists())
	{
	    Frame frame = Frame.getInstance();
	    String conf =
		    frame.getLanguageValue("confirmExistingFile") + " "
			    + file.getName();
	    String owrite = frame.getLanguageValue("overwriteExistingFile");

	    if (JOptionPane.showConfirmDialog(frame.getRootPane(), conf, owrite, 
		    JOptionPane.OK_CANCEL_OPTION) == JOptionPane.CANCEL_OPTION)
		return null;
	}

	return file;
    }

}
